/*
 * vector.c
 *
 *  Created on: May 7, 2010
 *      Author: cralix
 */

#include <stdlib.h>
#include <unistd.h>
#include "common.h"
#include "vector.h"


vector_p vector_new(void) {
	vector_p v;
	v = malloc(sizeof(vector_t));
	if (v == NULL)
		return NULL;

	v->data = calloc(DEFAULT_VECTOR_SIZE, sizeof(void *));
	if (v->data == NULL) {
		free(v);
		return NULL;
	}
	v->max = DEFAULT_VECTOR_SIZE;
	v->count = 0;
	return v;
}


int vector_len(vector_p v) {
	return (v != NULL) ? v->count : -1;
}

int vector_capacity(vector_p v) {
	return (v != NULL) ? v->max : -1;
}

return_t vector_resize(vector_p v, int size) {
	if (v == NULL)
		return RT_ERR;

	if (v->data == NULL) {
		v->data = calloc(size, sizeof(void *));
	} else {
		v->data = realloc(v->data, size * sizeof(void *));
	}
	v->max = size;
	if (v->count > v->max) {
		v->count = v->max;
	}
	return RT_OK;
}

return_t vector_add(vector_p v, void * value) {
	return vector_insert(v, value, v->count);
}

return_t vector_insert(vector_p v, void * value, int index) {
	int i;
	if (v == NULL) {
		return RT_ERR;
	}

	if (index < 0 || index > v->count) {
		return RT_ERR;
	}
	if (v->count >= v->max) {
		vector_resize(v, v->max + 10);
	}
	if (index < v->count) {
		for(i = v->count; i > index; i--) {
			*(v->data + i) = *(v->data + i-1);
		}
	}
	*(v->data + index) = value;
	v->count++;
	return RT_OK;
}

void * vector_get(vector_p v, int index) {
	if (v == NULL) {
		return NULL;
	}

	if (index < 0 || index >= v->count) {
		return NULL;
	}
	return *(v->data + index);
}

void * vector_set(vector_p v, void * value, int index) {
	void * p;

	if (v == NULL) {
		return NULL;
	}
	if (index < 0 || index >= v->count) {
		return NULL;
	}
	p = *(v->data + index);
	*(v->data + index) = value;
	return p;
}

void * vector_remove(vector_p v, int index) {
	int i;
	void * p;

	if (v == NULL) {
		return NULL;
	}

	if (index < 0 || index >= v->count) {
		return NULL;
	}

	p = *(v->data + index);
	for (i = index; i < v->count-1; i++) {
		*(v->data + i) = *(v->data + i+1);
	}
	v->count--;

	return p;
}

return_t vector_clear(vector_p v) {
	if (v == NULL) {
		return RT_ERR;
	}

	v->count = 0;
	return RT_OK;
}

void vector_delete(vector_p v) {
	if (v != NULL) {
		free(v->data);
		free(v);
	}
}

//void vector_print(vector_p v){
//	if (v != NULL){
//		int i;
//		for(i=0; i<v->count; i++){
//			fprintf(stdout, "", v->data);
//		}
//		fprintf(stdout, "\n");
//	}
//}

